package realm.inorder.itmill.ui.panel.logged.cadastro.cliente;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import realm.inorder.itmill.ui.menu.ComponentMenuOption;
import realm.inorder.itmill.ui.menu.MenuOption;
import realm.inorder.itmill.ui.menu.MenuPanel;
import realm.inorder.itmill.ui.menu.SimpleMenuOption;
import realm.inorder.persistence.model.Cliente;

import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.OrderedLayout;
import com.itmill.toolkit.ui.Button.ClickEvent;

@Component
public class ClienteConsultaPanel extends AbstractClientePanel implements InitializingBean {

	private ClienteTable clienteTable;
	
	@Autowired
	private ClienteController clienteController;
	
	@Autowired
	private MenuPanel menuPanel;
	
	public ClienteConsultaPanel() {
		super("Consulta por Clientes *");
	}
	
	public void afterPropertiesSet() throws Exception {
		refreshTable();
	}

	public void initComponents() {
		OrderedLayout layout = new OrderedLayout(OrderedLayout.ORIENTATION_VERTICAL);
		
		clienteTable = new ClienteTable();
		clienteTable.setHeight(300, UNITS_PIXELS);
		
		layout.addComponent(clienteTable);
		
		this.addComponent(layout);
	}
	
	public void refreshTable() {
		clienteController.updateClienteTable(clienteTable);
	}
	
	public void initActions() {
		clienteTable.addListener(new ValueChangeListener() {
			public void valueChange(ValueChangeEvent event) {
				if (event.getProperty().getValue() == null) {
					menuPanel.removeMenuOption(headerMenuOption);
					menuPanel.removeMenuOption(editarMenuOption);
				} else {
					logger.debug("Cliente: "+clienteTable.getSelectedItemId());
					menuPanel.addMenuOption(1, headerMenuOption);
					menuPanel.addMenuOption(2, editarMenuOption);
				}
				
				menuPanel.buildMenu();
			}
		});
	}

	private final MenuOption headerMenuOption = new ComponentMenuOption() {

		@Override
		public com.itmill.toolkit.ui.Component getComponent() {
			Label label = new Label("Cliente Selecionado *");
			label.setStyleName("menuheader");
			return label;
		}
		
	};
	
	private final MenuOption editarMenuOption = new SimpleMenuOption("Editar *") {
		@Override
		public void performAction(ClickEvent clickEvent) {
			// TODO buscar cliente e abrir tela de cadastro de cliente preenchida 
			Cliente cliente = clienteController.findClienteById(clienteTable.getSelectedItemId());
		}
	};

}
